package com.yvan.dev2word.swagger2doc.service.impl;

import com.yvan.dev2word.db2word.utils.JDBCUtils;
import com.yvan.dev2word.db2word.vo.Table;
import com.yvan.dev2word.db2word.vo.TableDesc;
import com.yvan.dev2word.swagger2doc.service.TableService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TableServiceImpl implements TableService {

    @Override
    public List<Table> findAllTable( DriverManagerDataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        String url = dataSource.getUrl();
        String dbName = JDBCUtils.findDBNameByUrl(url);
        String sql = "SELECT TABLE_NAME as tableName,TABLE_COMMENT as tableComment FROM information_schema.TABLES WHERE table_schema= '" + dbName + "';";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Table.class));
    }

    @Override
    public List<TableDesc> findByTableName(String tableName, DriverManagerDataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        String sql = "SHOW FULL FIELDS FROM " + tableName + ";";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TableDesc.class));
    }

    @Override
    public DriverManagerDataSource createDataSource(String jdbcUrl, String jdbcUsername, String jdbcPassword) {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(jdbcUrl);
        dataSource.setUsername(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        return dataSource;
    }

}
